package com.lindroy.androidplayer.logic.network2.state

import androidx.lifecycle.MutableLiveData
import com.lindroy.androidplayer.extensions.no
import com.lindroy.androidplayer.extensions.yes
import com.lindroy.androidplayer.logic.model.HttpResult
import com.lindroy.androidplayer.logic.network2.AppException
import com.lindroy.androidplayer.logic.network2.ExceptionHandle


/**
 * @author Lin
 * @date 2021/4/15
 * @function
 */
sealed class ResultState<out T> {
    companion object {
        fun <T> onSuccess(data: T): ResultState<T> = Success(data)
        fun <T> onLoading(loadingMsg: String): ResultState<T> = Loading(loadingMsg)
        fun <T> onError(error: AppException): ResultState<T> = Error(error)
    }
}

data class Loading(val loadingMsg: String) : ResultState<Nothing>()
data class Success<out T>(val data: T) : ResultState<T>()
data class Error(val error: AppException) : ResultState<Nothing>()

/**
 * 处理返回值
 */
fun <T> MutableLiveData<ResultState<T>>.requestResult(result: HttpResult<T>) {
    value = result.success.yes {
        ResultState.onSuccess(result.data)
    }.no {
        ResultState.onError(AppException(result.errorCode, result.errorMsg))
    }
}

/**
 * 不处理返回值 直接返回请求结果
 * @param result 请求结果
 */
fun <T> MutableLiveData<ResultState<T>>.paresResult(result: T) {
    value = ResultState.onSuccess(result)
}

/**
 * 直接返回异常结果
 * 异常转换异常处理
 */
fun <T> MutableLiveData<ResultState<T>>.paresException(e: Throwable) {
    this.value = ResultState.onError(ExceptionHandle.handleException(e))
}